# -*- coding:utf-8 -*-
# @Time : 2021-2-1 15:51
# @Author : suny570
# @Site   :
# @File : semantic_client.py
# @Software: PyCharm

#from app import app, root_path, semantic_faq
from app import app, root_path
from app.Logging import init_logger
import os
import json
import time
from json import JSONDecodeError
from flask import request, jsonify
from src.db_es.ElasticSearchClass import ElasticSearchClass
from src.intelligent_interaction.engine.loginfo_engine import LoginfoEngine
from src.intelligent_interaction.engine.semantic_search import SemanticSearch
import src.db_es.es_config as Config

logger=init_logger(root_path + '/Logs/semantic_faq_')

@app.route('/semantic_kg', methods=['POST'])
def faq_search():
    es_service_conn = ElasticSearchClass(Config.TEST_ONLINE_ES_HOST, Config.TEST_ONLINE_ES_PORT
                                         , Config.TEST_ONLINE_ES_USER, Config.TEST_ONLINE_ES_PASSWORD)

    loginfo_engine = LoginfoEngine(es_service_conn)
    log_data, data = {}, {}
    try:
        data = json.loads(request.get_data())
        log_data = {}
        log_data['id'] = None
        log_data['ip'] = str(request.remote_addr)
        log_data['query_info'] = str(data)
        log_data['service_name'] = "semantic_faq"
        log_data['time'] = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        # print(str(data))
        content = data["query"]
        if len(content) == 0:
            return_data = {"failDetail": '搜索文本长度为零，请输入要查询的内容。'}
            recognize_info = {"code": "0001", "message": "失败", "data": return_data}
            logger.warning(recognize_info)
            log_data['code'] = "0001"
            log_data['message'] = "失败"
            log_data['ret_data'] = str(return_data)
            loginfo_engine.write_search_info_into_es(data, log_data)
            #return jsonify(recognize_info), 200
        else:
            if len(content) > 128:
                content = content[0:127]
            # 搜索策略
            semantic_faq = SemanticSearch(es_service_conn)
            ret_json = semantic_faq.standard_search_inter(Config.ONLINE_ES_INDEX, Config.ONLINE_ES_TYPE, data, 9)

            if len(ret_json) > 0:
                return_data = ret_json
                recognize_info = {"code": "0000", "message": "成功", "data": return_data}
                log_data['code'] = "0000"
                log_data['message'] = "成功"
                log_data['ret_data'] = str(return_data)
                logger.info(recognize_info)

                loginfo_engine.write_search_info_into_es(data, log_data)

            else:
                return_data = {"failDetail": '没有查询到结果，请尝试其他检索词，输入内容为{}。'.format(len(content))}
                recognize_info = {"code": "0004", "message": "失败", "data": return_data}
                logger.warning(recognize_info)
                log_data['code'] = "0004"
                log_data['message'] = "失败"
                log_data['ret_data'] = str(return_data)
                logger.info(recognize_info)
                loginfo_engine.write_search_info_into_es(data, log_data)

    except JSONDecodeError as e:
        error_info = {"error": "输入数据格式错误,具体如下：{}".format(e.msg)}
        recognize_info = {"code": "0002", "message": "失败", "data": error_info}
        logger.warning(recognize_info)
        log_data['code'] = "0002"
        log_data['message'] = "失败"
        log_data['ret_data'] = str(error_info)
        loginfo_engine.write_search_info_into_es(data, log_data)
        # es_service_conn.close_connect()

    except Exception as e:
        error_info = {"error": "服务异常,具体如下：{0}".format(repr(e))}
        recognize_info = {"code": "0003", "message": "失败", "data": error_info}
        logger.warning(recognize_info)
        log_data['code'] = "0003"
        log_data['message'] = "失败"
        log_data['ret_data'] = str(error_info)
        loginfo_engine.write_search_info_into_es(data, log_data)
        # es_service_conn.close_connect()

    # es_service_conn.close_connect()
    return jsonify(recognize_info), 200


@app.route('/semantic_hot_top', methods=['POST'])
def semantic_hot_top():
    """
    热点搜索接口
    :return:
    """
    es_service_conn = ElasticSearchClass(Config.TEST_ONLINE_ES_HOST, Config.TEST_ONLINE_ES_PORT
                                         , Config.TEST_ONLINE_ES_USER, Config.TEST_ONLINE_ES_PASSWORD)  # ES引擎
    loginfo_engine = LoginfoEngine(es_service_conn)  # 日志引擎
    log_data = {}

    try:
        ret_json = []  # 返回内容
        with open(os.getcwd() + '/src/test.txt', 'r', encoding='utf-8') as f:
            for l in f.readlines():
                temp = {}
                temp['id'] = l.strip().split('|')[0]
                temp['standard_question'] = l.strip().split('|')[1]
                ret_json.append(temp)

        log_data['id'] = None
        log_data['ip'] = str(request.remote_addr)
        log_data['query_info'] = ''
        log_data['service_name'] = "semantic_hot"
        log_data['time'] = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

        return_data = ret_json
        recognize_info = {"code": "0000", "message": "成功", "data": return_data}  # 返回内容
    except JSONDecodeError as e:
        error_info = {"error": "服务异常,具体如下：{}".format(e.msg)}
        recognize_info = {"code": "0002", "message": "失败", "data": error_info}  # 返回内容
        logger.warning(recognize_info)
        log_data['code'] = "0002"
        log_data['message'] = "失败"
        log_data['ret_data'] = str(error_info)
        # es_service_conn.close_connect()

    # es_service_conn.close_connect()
    return jsonify(recognize_info), 200

